<template>
  <div>
    <el-card>
      <el-form class="demo-form-inline">
        <el-row>
          <el-form-item>
            <el-input
              placeholder="用户名"
              v-model="pageList.username"
              style="width: 160px"
              clearable
            >
            </el-input>
            <el-button
              type="primary"
              style="margin: 0 20px"
              size="small"
              @click="onSubmit"
              >查询</el-button
            >
            <el-button size="small" @click="resetSearch">清空</el-button>
          </el-form-item>
        </el-row>
      </el-form>

      <el-row style="margin: 20px 0">
        <el-button
          type="primary"
          size="medium"
          round
          @click="addDialogVisible = true"
          >添加</el-button
        >
        <el-button
          type="danger"
          :disabled="selectedIds.length == 0"
          size="medium"
          round
          @click="removeUsers"
          >批量删除</el-button
        >
      </el-row>

      <el-row>
        <el-table
          :data="userData.items"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />

          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          />

          <el-table-column prop="username" label="用户名" width="150" />
          <el-table-column prop="nickName" label="用户昵称" />
          <el-table-column prop="roleName" label="角色列表" width="200" />

          <el-table-column prop="gmtCreate" label="创建时间" width="180" />
          <el-table-column prop="gmtModified" label="更新时间" width="180" />

          <el-table-column
            label="操作"
            width="200"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                type="info"
                size="small"
                icon="el-icon-user-solid"
                @click="showAssignRole(scope.row)"
                title="分配角色"
              />
              <!-- 按照我的写法scope.row这个是当前行的数据 -->
              <el-button
                type="primary"
                size="small"
                icon="el-icon-edit"
                @click="
                  modifyDialogVisible = true;
                  ruleForm1.id = scope.row.id;
                "
                title="修改用户"
              />

              <el-button
                style="margin-left: 10px"
                type="danger"
                size="small"
                icon="el-icon-delete"
                @click="removeUserId(scope.row)"
                title="删除用户"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-row>

      <el-row :gutter="10">
        <el-pagination
          :current-page="pageList.page"
          :page-size="pageList.limit"
          :total="userData.total"
          :page-sizes="[5, 10, 20, 30]"
          style="padding: 20px 0"
          layout="prev, pager, next, jumper, ->, sizes, total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </el-row>

      <el-dialog :visible.sync="addDialogVisible" title="添加用户" top="0px">
        <!-- :title="userData.items.id ? '修改用户' : '添加用户'" -->
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="120px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username" />
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="ruleForm.nickName" />
          </el-form-item>

          <el-form-item label="用户密码" prop="password">
            <!-- v-if="!userData.items.id" -->
            <el-input v-model="ruleForm.password" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="AddUserData('ruleForm')"
              >确 定</el-button
            >
          </div>
        </template>
      </el-dialog>

      <el-dialog :visible.sync="modifyDialogVisible" title="修改用户" top="0px">
        <el-form
          :model="ruleForm1"
          :rules="rules1"
          ref="ruleForm1"
          label-width="120px"
          title="修改用户"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm1.username" />
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="ruleForm1.nickName" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="modifyDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="modifyUserData('ruleForm1')"
              >确 定</el-button
            >
          </div>
        </template>
      </el-dialog>

      <el-dialog title="设置角色" :visible.sync="setUpTableVisible" top="0px">
        <el-form label-width="80px">
          <el-form-item label="用户名">
            <el-input disabled :value="username"> </el-input>
          </el-form-item>

          <el-form-item label="角色列表">
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            >
            <div style="margin: 15px 0"></div>
            <el-checkbox-group
              v-model="jueSeSelected"
              @change="handleCheckedChange"
            >
              <el-checkbox
                v-for="allRole in allRolesList"
                :label="allRole"
                :key="allRole"
                >{{ allRole }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button type="primary" @click="SetRoles">保存</el-button>
          <el-button @click="setUpTableVisible = false">取消</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import { mapState } from "vuex";
import {
  SaveUser,
  RemoveUsers,
  RemoveUser,
  modifyUserData,
  GetUsersData,
  AssignUsers,
} from "@/api/userList";
//第二步把你鞋的方法引进来   穿了你那边没接收
export default {
  name: "Permission",
  data() {
    var validatePassword = (rule, value, callback) => {
      if (!value) {
        callback("密码必须输入");
      } else if (!value || value.length < 6) {
        callback("密码不能小于6位");
      } else {
        callback();
      }
    };
    return {
      addDialogVisible: false,
      modifyDialogVisible: false,
      setUpTableVisible: false,
      username: "",
      userId: "",
      checkAll: false,
      isIndeterminate: true,
      allRolesList: [], //这个是要的分配角色最后的数据
      jueSeSelected: [], //这个是选中的
      allList: [],

      // 分页、搜索
      pageList: {
        username: "",
        searchUsername: "",
        page: 1,
        limit: 5,
      },
      // 添加用户
      ruleForm: {
        username: "",
        password: "",
        nickName: "",
      },
      // 修改用户
      ruleForm1: {
        username: "",
        nickName: "",
        id: "",
      },
      ///添加用户验证
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        nickName: [
          { required: false, message: "请输入用户昵称", trigger: "blur" },
        ],
        password: [
          { required: true, validator: validatePassword, trigger: "blur" },
        ],
      },
      //修改用户验证
      rules1: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        nickName: [
          { required: false, message: "请输入用户昵称", trigger: "blur" },
        ],
      },
      // 删除多个
      selectedIds: [],
      // 获取
    };
  },

  mounted() {
    this.getUserData();
  },

  methods: {
    // 查询
    onSubmit() {
      let { pageList } = this;
      pageList.searchUsername = pageList.username;
      console.log(pageList.username);
      this.getUserData(pageList.username);
    },

    // 清空
    resetSearch() {
      let { pageList } = this;
      pageList.username = "";
      pageList.searchUsername = "";
      this.getUserData();
    },

    //分页
    handleSizeChange(val) {
      this.pageList.limit = val;
      this.getUserData();
    },
    handleCurrentChange(val) {
      console.log(val);
      this.pageList.page = val;
      this.getUserData();
    },

    // 批量删除
    handleSelectionChange(val) {
      if (val.length == 0) {
        this.selectedIds = [];
        return;
      }
      val.map((item, index) => {
        this.selectedIds.push(item.id);
      });
      // this.multipleSelection = val;
    },
    // 获取用户列表
    getUserData(name) {
      ///user/1/23?username=828282   前面传参数的时候直接就是后面跟第几页和多少条就行     这个名字需要给定username不然后端不知道你穿的是名字还是昵称   后面传昵称的时候也是这么传就后面跟个？nicheng=啥啥啥
      let { pageList } = this;
      this.$store.dispatch("conten/getUserData", pageList, {
        username: name,
      });
    },

    SetRoles() {},
    // 增加用户
    AddUserData(formName) {
      let _this = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          SaveUser(_this.ruleForm).then((res) => {
            _this.addDialogVisible = false;
            _this.$message({
              showClose: true,
              message: "添加用户成功",
              type: "success",
            });
            _this.getUserData();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //修改用户
    modifyUserData(formName) {
      let _this = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          modifyUserData(_this.ruleForm1).then((res) => {
            _this.modifyDialogVisible = false;
            _this.$message({
              showClose: true,
              message: "修改用户成功",
              type: "success",
            });
            _this.getUserData();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 批量删除
    removeUsers() {
      let _this = this;
      this.$confirm("确定要批量删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          RemoveUsers(this.selectedIds).then((res) => {
            this.$message({
              showClose: true,
              type: "success",
              message: "删除成功!",
            });
            _this.getUserData();
          });
        })
        .catch(() => {
          this.$message({
            showClose: true,
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 删除单个用户
    removeUserId(data) {
      let _this = this;
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          RemoveUser(data.id).then((res) => {
            this.$message({
              showClose: true,
              type: "success",
              message: "删除成功!",
            });
            _this.getUserData();
          });
        })
        .catch(() => {
          this.$message({
            showClose: true,
            type: "info",
            message: "已取消删除",
          });
        });

      // removeUser = async (id) => {
      // await removeUserApi(id)
      // ElMessage.success('删除成功')
      // this.getUserData(.length===1 ? pageList.page-1 : pageList.page)
    },

    // 设置角色
    showAssignRole(data) {
      this.username = data.username;
      this.userId = data.id;
      //这个data是你要接收的你要传的id
      this.setUpTableVisible = true; //这个要用this
      GetUsersData(data.id).then((res) => {
        //把你的id传过去
        console.log(res.data); //请求成功后把数据拿出来在做个处理
        res.data.allRolesList.forEach((item) => {
          if (item.roleName !== "") {
            if (this.allRolesList.indexOf(item.roleName) == -1) {
              this.allRolesList.push(item.roleName);
              this.allList.push(item);
            }
          }
        });
      });
    },

    handleCheckAllChange(val) {
      this.jueSeSelected = val ? this.allRolesList : [];
      this.isIndeterminate = false;
    },
    handleCheckedChange(value) {
      console.log(value);
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.allRolesList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.allRolesList.length;
    },

    SetRoles() {
      let idList = [];
      this.allList.forEach((item) => {
        this.jueSeSelected.forEach((item1) => {
          if (item1 == item.roleName) {
            idList.push(item.id);
          }
        });
      });
      let data = {
        userId: this.userId,
        roleId: idList.toString(),
      };
      let _this = this;
      AssignUsers(data)
        .then((res) => {
          this.setUpTableVisible = false;
          this.$message({
            showClose: true,
            type: "success",
            message: "角色分配成功",
          });
          console.log(data);
          _this.getUserData();
        })
        .catch(() => {
          this.$message({
            showClose: true,
            type: "info",
            message: "保存失败",
          });
        });
    },
  },

  computed: {
    ...mapState("conten", ["userData"]),
  },
};
</script>

